package com.cff.shorturl.service.imp;

import java.sql.SQLException;

import com.cff.shorturl.db.DbFactory;
import com.cff.shorturl.db.DbManager;
import com.cff.shorturl.http.body.HttpRequestMsg;
import com.cff.shorturl.http.body.HttpResponseMsg;
import com.cff.shorturl.service.Service;
import com.cff.shorturl.util.StringUtil;

public class RedirectService implements Service {

	@Override
	public HttpResponseMsg handler(HttpRequestMsg httpRequestMsg) {
		try {
			String path = httpRequestMsg.getUrl();
			if (!path.matches("[0-9a-zA-Z]{4,10}"))
				return null;
			String sql = "select url from t_short_url where surl = ?";
			DbManager db = DbFactory.createDbManager();
			String url = db.queryString(sql, new Object[]{path});
			if(StringUtil.isEmpty(url))return null;
			HttpResponseMsg hrm = httpRequestMsg.getReponse();
			hrm.setRedirect(url);
			return hrm;
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
	}

}
